package com.example.demo.util;

import java.io.FileInputStream;
import java.io.InputStream;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.example.demo.entity.oss.OSSResultEntity;

/**
 * 
 * @title:	OSSUtils
 * @author:	许子文
 * @date:	2021年10月2日 
 * @descirption: OSS文件管理工具类
 *
 */
public class OSSUtils {
	
	/**
	 * 
	 * @title downloadFile
	 * @author: 许子文
	 * @date: 2021年10月8日
	 * @description: 根据OSS的key获取文件流
	 *
	 */
	public static InputStream downloadFile(String ossKey) {
		String endpoint = PropertiesUtil.getProperty("oss.endpoint");
		String accessKeyId = PropertiesUtil.getProperty("oss.accessKeyId");
		String accessKeySecret = PropertiesUtil.getProperty("oss.accessKeySecret");
		String bucketName = PropertiesUtil.getProperty("oss.bucketName");
		
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		
		OSSObject ossObject = ossClient.getObject(bucketName, ossKey);
		
		InputStream in = ossObject.getObjectContent();
		
		return in;
	}
	
	/**
	 * 
	 * @title uploadFile
	 * @author: 许子文
	 * @date: 2021年10月2日
	 * @description: 上传文件流到oss,并返回访问文件的http链接
	 *
	 */
	public static OSSResultEntity uploadFile (InputStream in,String moduleName,String fileFormat) throws Exception{
		String endpoint = PropertiesUtil.getProperty("oss.endpoint");
		String accessKeyId = PropertiesUtil.getProperty("oss.accessKeyId");
		String accessKeySecret = PropertiesUtil.getProperty("oss.accessKeySecret");
		String bucketName = PropertiesUtil.getProperty("oss.bucketName");
		
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		
		String nowDay = DateUtil.getNowDayWithoutLink();
		
		String ossKey = null;
		
		if(fileFormat.startsWith(".")) {
			ossKey = moduleName + "/" +nowDay + "/" + PrimaryKeyUtil.getUUIDWithOutLink() + fileFormat;
		} else {
			ossKey = moduleName + "/" +nowDay + "/" + PrimaryKeyUtil.getUUIDWithOutLink() + "." + fileFormat;
		}
		
		ossClient.putObject(bucketName, ossKey, in);
		
		ossClient.shutdown();
		
		StringBuilder fileReqUrl = new StringBuilder();
		
		fileReqUrl.append("https://")
				.append(bucketName)
				.append(".")
				.append(endpoint)
				.append("/")
				.append(ossKey);
		
		OSSResultEntity ossret = new OSSResultEntity(ossKey, fileReqUrl.toString());
		
		return ossret;
	}
	
	public static void main(String[] args) throws Exception {
		PropertiesUtil.initProperty();
		
		InputStream in = new FileInputStream("D:\\图片\\发票\\南京肯德基有限公司安徽分公司增值税电子普通发票.pdf");
		
		String format = "pdf";
		
		OSSResultEntity fileUrl = uploadFile(in, "invoice", format);
		
		System.out.println(fileUrl);
		
	}
}
